//
//  ANMainController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/10.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANMainController.h"
#import <CoreLocation/CoreLocation.h>
#import "MainSearchView.h"
#import "MainGoodsFilterView.h"
#import "MainGoodsCell.h"
#import "MainHeaderView.h"
#import "GoodsEntity.h"
#import "ANGoodsInfoController.h"
#import "DropDownView.h"
#import "GoodsTypeEntity.h"
#import "ANMessageCenterController.h"
#import "UIView+Badge.h"

@interface ANMainController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate,MainSearchViewDelegate>

@property (nonatomic, strong) UIButton *messageBtn;

@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, strong) MainSearchView *searchView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MainGoodsFilterView *filterView;
@property (nonatomic, strong) DropDownView *dropDownView;
@property (nonatomic, strong) MainHeaderView *headerView;
@property (nonatomic, strong) NSArray *imageUrlStrings;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic) int pageNo;

@property (nonatomic, copy) NSString *searchText;
@property (nonatomic, strong) NSIndexPath *selectGoodsTypeIndex;
@property (nonatomic, strong) NSArray<GoodsTypeEntity *> *goodsTypeDataSource;
@property (nonatomic, copy) NSString *orderBy;//销量
@property (nonatomic, copy) NSString *goodsTypeId;//商品类型ID

@end

@implementation ANMainController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"首页";
    self.pageNo = 1;
    self.dataSource = @[].mutableCopy;
    self.searchText = @"";
    self.orderBy = kSaleNornalState;
    self.goodsTypeId = @"";
    
    
    [self requestGoodsList];
    [self requestCycImage];
    
    [self startLocation];
    
    // 极光自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self requestUnReadMessageCount];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification
{
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    if ([message.allKeys containsObject:@"pushType"] && [message[@"pushType"] intValue] == 1 && [message[@"messageSource"] intValue] == 1) {
        NSLog(@"收到新的未读消息消息：%@",content);
        self.messageBtn.showDot = @(YES);
    }
}

- (void)startLocation
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    [self.locationManager requestWhenInUseAuthorization];
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
    }
}

/** 定位服务状态改变时调用*/
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        {
            NSLog(@"用户还未决定授权");
            break;
        }
        case kCLAuthorizationStatusRestricted:
        {
            NSLog(@"访问受限");
            break;
        }
        case kCLAuthorizationStatusDenied:
        {
            // 类方法，判断是否开启定位服务
            if ([CLLocationManager locationServicesEnabled]) {
                NSLog(@"定位服务开启，被拒绝");
            } else {
                NSLog(@"定位服务关闭，不可用");
            }
            UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"定位服务未开启" message:@"请在系统设置中开启定位服务" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"暂不" style:UIAlertActionStyleDefault handler:nil];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [[NSURL alloc] initWithString:UIApplicationOpenSettingsURLString];
                if( [[UIApplication sharedApplication] canOpenURL:url]) {
                    if (@available(iOS 10.0, *)) {
                        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                            NSLog(@"success:%d", success);
                        }];
                    } else {
                        [[UIApplication sharedApplication] openURL:url];
                    }
                }
            }];
            [vc addAction:action1];
            [vc addAction:action2];
            [self presentViewController:vc animated:YES completion:nil];
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways:
        {
            NSLog(@"获得前后台授权");
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            NSLog(@"获得前台授权");
            break;
        }
        default:
            break;
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations firstObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error) {
            self.searchView.city = placemarks.firstObject.locality;
        }
    }];
}

- (void)dropDown
{
    self.dropDownView.selectIndexPath = self.selectGoodsTypeIndex;
    self.dropDownView.hidden = NO;
    CGRect rect = [self.tableView convertRect:self.filterView.frame toView:self.view];
    self.dropDownView.showRect = CGRectMake(0, rect.origin.y+self.filterView.frame.size.height, rect.size.width, self.dropDownView.frame.size.height-CGRectGetMaxY(rect));
    self.dropDownView.goodsTypeDataSource = self.goodsTypeDataSource;
}

- (void)requestUnReadMessageCount
{
    NSDictionary *body = @{
                           @"messageSource":@"1"
                           };
    [URLManager.shareManager getUrlStr:Api_Get_Unread_Message_Count parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                if ([responseObj[@"data"] intValue] > 0) {
                    self.messageBtn.showDot = @(YES);
                }
                else {
                    self.messageBtn.showDot = @(NO);
                }
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

- (void)requestCycImage
{
    [URLManager.shareManager getUrlStr:Api_Main_Cyc_Image parameters:nil success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        
        
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                NSMutableArray *temp = @[].mutableCopy;
                NSArray *data = responseObj[@"data"];
                for (int i = 0; i < data.count; i++) {
                    NSDictionary *dict = data[i];
                    NSString *url = [NSString stringWithFormat:@"%@%@",SERVERADDRS,dict[@"filePath"]];
                    [temp addObject:url];
                }
                self.imageUrlStrings = temp.copy;
                self.headerView.imageUrlStrings = self.imageUrlStrings;
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}
- (void)requestGoodsType
{
    [MBProgressHUD showActivityMessage:nil];
    NSDictionary *para = @{
                           @"categroyCode":@"goodsType",//模糊查询
                           };
    [URLManager.shareManager getUrlStr:Api_Data_Dictionary parameters:para entityClass:[GoodsTypeEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        [MBProgressHUD hideHUD];
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                NSArray *data = baseEntity.data;
                if (data && data.count) {
                    self.goodsTypeDataSource = data;
                    [self dropDown];
                }
            }
        }
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
    }];
}

- (void)requestGoodsList
{
    NSString *goodsTypeId = @"";
    if (self.goodsTypeDataSource && self.goodsTypeDataSource.count) {
        goodsTypeId = self.goodsTypeDataSource[self.selectGoodsTypeIndex.row].dictId;
    }
    NSDictionary *para = @{
                           @"goodsName":self.searchText,//模糊查询
                           @"goodsTypeId":goodsTypeId,//商品类型id
                           @"orderBy":self.orderBy,//排序 已售数量  soldNum desc 降序 soldNum  asc 升序
                           @"pageNo":@(self.pageNo),
                           @"pageSize":@20
                           };
    [URLManager.shareManager getUrlStr:Api_Goods_List parameters:para entityClass:[GoodsListEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                GoodsListEntity *data = baseEntity.data;
                if (self.pageNo == 1) {
                    [self.dataSource removeAllObjects];
                    [self.tableView.mj_footer resetNoMoreData];
                    [self.tableView.mj_header endRefreshing];
                    if (data.data.count < 20) {
                        self.tableView.mj_footer.alpha = 0;
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
                else {
                    if (data.data.count < 20) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    else {
                        [self.tableView.mj_footer endRefreshing];
                    }
                }
                [self.dataSource addObjectsFromArray:data.data];
                [self.tableView reloadData];
            }
            else {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
        }
        else {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)gotoMessageCenter
{
    ANMessageCenterController *vc = [[ANMessageCenterController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setupSubViews
{
    self.messageBtn = [[UIButton alloc] init];
    self.messageBtn.badgeOriginX = @12;
    self.messageBtn.badgeOriginY = @(-4);
    [self.messageBtn setImage:[UIImage imageNamed:@"kefu"] forState:UIControlStateNormal];
    [self.messageBtn addTarget:self action:@selector(gotoMessageCenter) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.messageBtn];
    
    self.searchView = [[MainSearchView alloc] init];
    [self.view addSubview:self.searchView];
    self.searchView.delegate = self;
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.equalTo(@44);
    }];
    WeakSelf
    self.searchView.searchHandler = ^(NSString * _Nonnull text) {
        weakSelf.searchText = text;
        weakSelf.pageNo = 1;
        [weakSelf requestGoodsList];
    };
    
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MainGoodsCell class] forCellReuseIdentifier:@"aa"];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    self.headerView = [[MainHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 140/375.0*kScreenW+kWidth(20)+30)];
    self.tableView.tableHeaderView = self.headerView;
    
    self.filterView = [[MainGoodsFilterView alloc] init];
    self.filterView.selectAll = YES;
    self.filterView.selectSale = kSaleNornalState;
    self.filterView.selectType = kTypeNormalState;
    
    self.headerView.imageUrlStrings = self.imageUrlStrings;
}

#pragma mark - MainSearchViewDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.searchText = searchText;
    self.pageNo = 1;
    [self requestGoodsList];
}


#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aa" forIndexPath:indexPath];
    [cell setShowShopName:NO];
    cell.entity = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GoodsEntity *goods = self.dataSource[indexPath.row];
    ANGoodsInfoController *vc = [[ANGoodsInfoController alloc] init];
    vc.goodsEntity = goods;
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kWidth(100);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    WeakSelf
    self.filterView.allHandler = ^{
        weakSelf.goodsTypeDataSource = nil;
        weakSelf.selectGoodsTypeIndex = nil;
        weakSelf.orderBy = @"";
        
        weakSelf.filterView.selectAll = YES;
        weakSelf.filterView.selectSale = kSaleNornalState;
        weakSelf.filterView.selectType = kTypeNormalState;
        
        [weakSelf requestGoodsList];
    };
    self.filterView.saleHandler = ^{
//        weakSelf.goodsTypeDataSource = nil;
//        weakSelf.selectGoodsTypeIndex = nil;
        if (weakSelf.orderBy == kSaleNornalState) {
            weakSelf.orderBy = kSaleUpState;
        }
        else if (weakSelf.orderBy == kSaleUpState) {
            weakSelf.orderBy = kSaleDownState;
        }
        else if (weakSelf.orderBy == kSaleDownState) {
            weakSelf.orderBy = kSaleUpState;
        }
        
        weakSelf.filterView.selectAll = NO;
        weakSelf.filterView.selectSale = weakSelf.orderBy;
//        weakSelf.filterView.selectType = kTypeNormalState;
        
        [weakSelf requestGoodsList];
    };
    self.filterView.typeHandler = ^{
        [weakSelf requestGoodsType];
    };
    
    
    return self.filterView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, kTabBarHeight, 0);
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.pageNo = 1;
            [weakSelf requestGoodsList];
            [weakSelf requestCycImage];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            weakSelf.pageNo++;
            [weakSelf requestGoodsList];
        }];;
    }
    return _tableView;
}

- (DropDownView *)dropDownView
{
    if (!_dropDownView) {
        _dropDownView = [[DropDownView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH-kStatusAndNavBarHeight-kTabBarHeight)];
        _dropDownView.hidden = YES;
        [self.view addSubview:_dropDownView];
        WeakSelf
        _dropDownView.selectHandler = ^(NSIndexPath * _Nonnull indexPath) {
//            weakSelf.orderBy = kSaleNornalState;
            
            weakSelf.filterView.selectAll = NO;
//            weakSelf.filterView.selectSale = weakSelf.orderBy;
            weakSelf.filterView.selectType = weakSelf.goodsTypeDataSource[indexPath.row].name;
            
            weakSelf.dropDownView.hidden = YES;
            weakSelf.selectGoodsTypeIndex = indexPath;
            [weakSelf.tableView reloadData];
            weakSelf.pageNo = 1;
            [weakSelf requestGoodsList];
        };
    }
    return _dropDownView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
